﻿@*
    For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
	Layout = null;
}
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>生产派单查询</title>
	<link href="~/scripts/layui-v2.5.6/layui/css/layui.css" rel="stylesheet" />
	<style>
		.search-form {
			padding: 15px;
			background-color: #f8f8f8;
			margin-bottom: 15px;
		}

		.table-container {
			padding: 0 15px;
		}

		.layui-table-cell {
			height: auto !important;
			white-space: normal;
		}

		.operation-btn {
			margin-right: 5px;
		}

		/* 主行样式 */
		.main-row {
			background-color: #f8f9fa !important;
			font-weight: normal;
			border-bottom: 1px solid #e9ecef;
		}

		/* 子行样式 */
		.sub-row {
			background-color: #fff !important;
			border-bottom: 1px solid #f1f1f1;
		}

		/* 展开/收起图标样式 */
		.expand-icon {
			cursor: pointer !important;
			margin-right: 8px;
			color: #666;
			font-size: 14px;
			transition: all 0.3s;
			display: inline-block;
			width: 18px;
			height: 18px;
			text-align: center;
			line-height: 18px;
			border-radius: 2px;
		}

			.expand-icon:hover {
				background-color: #f0f0f0;
				color: #1E9FFF !important;
			}

		/* 主行工单编号容器样式 */
		.main-row-workorder {
			cursor: pointer;
			padding: 2px 0;
		}

			.main-row-workorder:hover {
				background-color: rgba(30, 159, 255, 0.1);
			}

		/* 隐藏子行的默认样式 */
		.sub-row-hidden {
			display: none !important;
		}

		/* 确保展开图标可点击 */
		.expand-icon {
			cursor: pointer !important;
			user-select: none;
			-webkit-user-select: none;
			-moz-user-select: none;
			-ms-user-select: none;
		}

			.expand-icon:hover {
				color: #1E9FFF !important;
			}

		/* 主行工单编号样式 */
		.main-row-workorder {
			display: flex;
			align-items: center;
		}

		/* 子行工单编号缩进样式 */
		.sub-row .layui-table-cell[data-field="productionWorkOrderCode"] {
			padding-left: 40px !important;
		}
	</style>
</head>
<body>
	<!-- 搜索区域 -->
	<div class="search-form">
		<form class="layui-form" lay-filter="searchForm">
			<div class="layui-form-item">
				<div class="layui-inline">
					<label class="layui-form-label">任务名称</label>
					<div class="layui-input-inline">
						<input type="text" name="taskName" placeholder="请输入任务名称" autocomplete="off" class="layui-input">
					</div>
				</div>
				<div class="layui-inline">
					<label class="layui-form-label">生产工单编号</label>
					<div class="layui-input-inline">
						<input type="text" name="workOrderCode" placeholder="请输入生产工单编号" autocomplete="off" class="layui-input">
					</div>
				</div>
				<div class="layui-inline">
					<label class="layui-form-label">工序名称</label>
					<div class="layui-input-inline">
						<select name="processName">
							<option value="">请选择工序名称</option>
							<option value="1">印刷</option>
							<option value="2">复合</option>
							<option value="3">分切</option>
							<option value="4">制袋</option>
						</select>
					</div>
				</div>
				<div class="layui-inline">
					<label class="layui-form-label">工单名称</label>
					<div class="layui-input-inline">
						<input type="text" name="workOrderName" placeholder="请输入工单名称" autocomplete="off" class="layui-input">
					</div>
				</div>
				<div class="layui-inline">
					<button class="layui-btn" lay-submit lay-filter="search">
						<i class="layui-icon layui-icon-search"></i>搜索
					</button>
					<button type="reset" class="layui-btn layui-btn-primary">
						<i class="layui-icon layui-icon-refresh"></i>重置
					</button>
				</div>
			</div>
		</form>
	</div>

	<!-- 数据表格区域 -->
	<div class="table-container">
		<table class="layui-hide" id="dispatchTreeTable" lay-filter="dispatchTreeTable"></table>
	</div>

	<!-- 表头工具栏模板 -->
	<script type="text/html" id="toolbarTpl">
		<div class="layui-btn-container">
			<button class="layui-btn layui-btn-sm" lay-event="getChecked">
				<i class="layui-icon layui-icon-edit"></i>批量编辑指派人
			</button>
			<button class="layui-btn layui-btn-danger layui-btn-sm" lay-event="batchDelete">
				<i class="layui-icon layui-icon-delete"></i>重置派单人
			</button>
		</div>
	</script>

	<!-- 操作列模板 -->
	<script type="text/html" id="operationTpl">
		{{# if(d.isParentRow) { }}
			<!-- 父级行显示添加子级按钮 -->
			<div class="layui-btn-container">
				<a class="layui-btn layui-btn-xs" lay-event="addChild" style="background-color: #009688; border-color: #009688;">
					<i class="layui-icon layui-icon-add-1"></i>添加子级
				</a>
			</div>
		{{# } else { }}
			<!-- 子级行显示修改和删除按钮 -->
			<div class="layui-btn-container">
				<a class="layui-btn layui-btn-xs" lay-event="edit" style="background-color: #1E9FFF; border-color: #1E9FFF;">
					修改
				</a>
				<a class="layui-btn layui-btn-xs" lay-event="delete" style="background-color: #FF5722; border-color: #FF5722;">
					重置派单人
				</a>
			</div>
		{{# } }}
	</script>

	<!-- 工单编号列模板 -->
	<script type="text/html" id="workOrderCodeTpl">
		{{# if(d.isParentRow) { }}
			<div class="main-row-workorder">
				<i class="layui-icon layui-icon-up expand-icon expanded"
				   data-workorder="{{= d.productionWorkOrderCode }}"
				   onclick="window.toggleSubRows('{{= d.productionWorkOrderCode }}', this); return false;"
				   title="点击展开/收起子级行"></i>
				<span>{{= d.productionWorkOrderCode }}</span>
			</div>
		{{# } else { }}
			<span style="padding-left: 20px;">{{= d.productionWorkOrderCode }}</span>
		{{# } }}
	</script>

	<!-- 工序名称模板 -->
	<script type="text/html" id="processNameTpl">
		{{# if(d.isParentRow) { }}
			<span style="color: #ccc;">-</span>
		{{# } else if(d.documentStatus == 1) { }}
			印刷
		{{# } else if(d.documentStatus == 2) { }}
			复合
		{{# } else if(d.documentStatus == 3) { }}
			分切
		{{# } else if(d.documentStatus == 4) { }}
			制袋
		{{# } else { }}
			{{= d.documentStatus || '' }}
		{{# } }}
	</script>

	<!-- 任务名称模板 -->
	<script type="text/html" id="taskNameTpl">
		{{# if(d.isParentRow) { }}
			<span style="color: #999; font-size: 12px;">[{{= d.childCount }}个子级任务]</span>
		{{# } else { }}
			{{= d.taskName }}
		{{# } }}
	</script>

	<!-- 工作站名称模板 -->
	<script type="text/html" id="workGroupNameTpl">
		{{# if(d.isParentRow) { }}
			<span style="color: #ccc;">-</span>
		{{# } else { }}
			{{= d.workGroupName }}
		{{# } }}
	</script>

	<!-- 产品物料名称模板 -->
	<script type="text/html" id="productMaterialNameTpl">
		{{# if(d.isParentRow) { }}
			<span style="color: #ccc;">-</span>
		{{# } else { }}
			{{= d.productMaterialName }}
		{{# } }}
	</script>

	<!-- 开始生产时间模板 -->
	<script type="text/html" id="productionStartTimeTpl">
		{{# if(d.isParentRow) { }}
			<span style="color: #ccc;">-</span>
		{{# } else { }}
			{{# if(d.productionStartTime) { }}
				{{= new Date(d.productionStartTime).toLocaleString('zh-CN') }}
			{{# } }}
		{{# } }}
	</script>

	<!-- 完成生产时间模板 -->
	<script type="text/html" id="productionEndTimeTpl">
		{{# if(d.isParentRow) { }}
			<span style="color: #ccc;">-</span>
		{{# } else { }}
			{{# if(d.productionEndTime) { }}
				{{= new Date(d.productionEndTime).toLocaleString('zh-CN') }}
			{{# } }}
		{{# } }}
	</script>

	<!-- 派单人名称模板 -->
	<script type="text/html" id="orderTargetTpl">
		{{# if(d.isParentRow) { }}
			<span style="color: #ccc;">-</span>
		{{# } else { }}
			{{= d.orderTarget }}
		{{# } }}
	</script>

	<script src="~/scripts/jquery-3.4.1.min.js"></script>
	<script src="~/scripts/layui-v2.5.6/layui/layui.js"></script>
	<script>
		layui.use(['table', 'form', 'layer'], function(){
			var table = layui.table;
			var form = layui.form;
			var layer = layui.layer;

			// 渲染数据表格
			var tableIns = table.render({
				elem: '#dispatchTreeTable',
				url: '/ProductionDispatchMain/GetDispatchList',
				method: 'GET',
				toolbar: '#toolbarTpl',
				height: 'full-200',
				page: true,
				limits: [10, 20, 50, 100],
				limit: 10,
				cols: [[
					{type: 'checkbox', fixed: 'left', width: 50},
					{field: 'productionWorkOrderCode', title: '生产工单编号', width: 180, sort: true, templet: '#workOrderCodeTpl'},
					{field: 'workOrderName', title: '工单名称', width: 150},
					{field: 'taskName', title: '任务名称', width: 150, templet: '#taskNameTpl'},
					{field: 'workGroupName', title: '工作站名称', width: 120, templet: '#workGroupNameTpl'},
					{field: 'documentStatus', title: '工序名称', width: 100, templet: '#processNameTpl'},
					{field: 'productMaterialName', title: '产品物料名称', width: 150, templet: '#productMaterialNameTpl'},
					{field: 'productionStartTime', title: '开始生产时间', width: 160, templet: '#productionStartTimeTpl'},
					{field: 'productionEndTime', title: '完成生产时间', width: 160, templet: '#productionEndTimeTpl'},
					{field: 'orderTarget', title: '派单人名称', width: 120, templet: '#orderTargetTpl'},
					{title: '操作', width: 200, toolbar: '#operationTpl', fixed: 'right', align: 'center'}
				]],
				parseData: function(res) {
					// 处理数据，实现分层显示效果
					console.log('原始API返回数据:', res);
					if(res.data && res.data.length > 0) {
						console.log('第一条原始数据:', res.data[0]);
						console.log('第一条数据的所有属性:', Object.keys(res.data[0]));
					}

					var processedData = [];
					var groupedData = {};

					// 按工单编号分组
					if(res.data && res.data.length > 0) {
						res.data.forEach(function(item) {
							if(!groupedData[item.productionWorkOrderCode]) {
								groupedData[item.productionWorkOrderCode] = [];
							}
							groupedData[item.productionWorkOrderCode].push(item);
						});

						// 按工单编号排序
						var sortedWorkOrderCodes = Object.keys(groupedData).sort();

						// 生成分层数据结构
						sortedWorkOrderCodes.forEach(function(workOrderCode) {
							var group = groupedData[workOrderCode];

							// 无论是单条还是多条数据，都创建父子结构
							var firstItem = group[0];
							var taskNames = group.map(function(item) { return item.taskName; }).filter(function(name) { return name; });
							var workGroups = group.map(function(item) { return item.workGroupName; }).filter(function(name) { return name; });
							var processes = group.map(function(item) { return item.documentStatus; }).filter(function(status) { return status; });
							var materials = group.map(function(item) { return item.productMaterialName; }).filter(function(name) { return name; });
							var targets = group.map(function(item) { return item.orderTarget; }).filter(function(name) { return name; });

							// 获取时间范围
							var startTimes = group.map(function(item) { return item.productionStartTime; }).filter(function(time) { return time; });
							var endTimes = group.map(function(item) { return item.productionEndTime; }).filter(function(time) { return time; });
							var earliestStart = startTimes.length > 0 ? Math.min.apply(Math, startTimes.map(function(t) { return new Date(t).getTime(); })) : null;
							var latestEnd = endTimes.length > 0 ? Math.max.apply(Math, endTimes.map(function(t) { return new Date(t).getTime(); })) : null;

							// 添加父级行（只显示工单编号和工单名称）
							processedData.push({
								id: 'parent_' + workOrderCode,
								productionWorkOrderCode: workOrderCode,
								workOrderName: firstItem.workOrderName || '工单汇总',
								taskName: '', // 父级行不显示任务名称
								workGroupName: '', // 父级行不显示工作站
								documentStatus: '', // 父级行不显示工序
								productMaterialName: '', // 父级行不显示物料
								productionStartTime: null, // 父级行不显示时间
								productionEndTime: null, // 父级行不显示时间
								orderTarget: '', // 父级行不显示派单人
								childCount: group.length, // 子级数量
								isMainRow: true,
								isParentRow: true,
								LAY_CHECKED: false
							});

							// 添加子级行（具体派单记录）
							group.forEach(function(item, index) {
								// 创建子级行的副本，避免修改原始数据
								// 确保使用原始数据的真实ID
								var realId = item.id || item.Id;
								console.log('处理子级行，原始item:', item, '真实ID:', realId);

								var childItem = {
									id: realId,
									Id: realId, // 同时设置大写和小写ID
									productionWorkOrderCode: workOrderCode,
									workOrderName: item.workOrderName,
									taskName: item.taskName,
									workGroupName: item.workGroupName,
									documentStatus: item.documentStatus,
									productMaterialName: item.productMaterialName,
									productionStartTime: item.productionStartTime,
									productionEndTime: item.productionEndTime,
									orderTarget: item.orderTarget,
									isMainRow: false,
									isParentRow: false,
									parentWorkOrderCode: workOrderCode,
									LAY_CHECKED: false
								};
								processedData.push(childItem);
							});
						});
					}

					return {
						code: 0,
						msg: res.msg || '',
						count: res.count || processedData.length,
						data: processedData
					};
				},
								done: function(res, curr, count) {
					// 表格渲染完成后，设置行样式
					setTimeout(function() {
						var $tableView = $('#dispatchTreeTable').next('.layui-table-view');
						var $tbody = $tableView.find('.layui-table-body tbody');

						$tbody.find('tr').each(function() {
							var $row = $(this);
							var index = $row.data('index');
							if(typeof index !== 'undefined') {
								var data = table.cache.dispatchTreeTable[index];
								if(data && data.isParentRow) {
									// 父级行样式
									$row.addClass('main-row');
									$row.find('td[data-field="0"] .layui-form-checkbox').hide(); // 隐藏父级行复选框
								} else if(data && data.parentWorkOrderCode) {
									// 子级行样式
									$row.addClass('sub-row');
									// 子级行显示复选框，可以选中
									// 默认显示子级行（展开状态）
								}
							}
						});

						console.log('表格渲染完成');
						console.log('找到的表格行数:', $tbody.find('tr').length);
						console.log('找到的展开图标数量:', $('.expand-icon').length);
						console.log('表格缓存数据:', table.cache.dispatchTreeTable);

						// 确保三角形图标可以点击
						$('.expand-icon').each(function() {
							console.log('找到三角形图标:', $(this).data('workorder'));
						});
					}, 200);
				}
			});

			// 全局展开/收起功能
			window.toggleSubRows = function(workOrderCode, iconElement) {
				var $icon = $(iconElement);
				var isExpanded = $icon.hasClass('expanded');

				console.log('=== 三角形点击事件触发 ===');
				console.log('工单编号:', workOrderCode);
				console.log('当前状态:', isExpanded ? '展开' : '收起');
				console.log('图标元素:', $icon);

				if(isExpanded) {
					// 收起子级行
					$icon.removeClass('expanded');
					$icon.removeClass('layui-icon-up').addClass('layui-icon-down');

					// 查找并隐藏子级行
					$('#dispatchTreeTable').next('.layui-table-view').find('.layui-table-body tbody tr').each(function() {
						var $row = $(this);
						var index = $row.data('index');
						if(typeof index !== 'undefined') {
							var data = table.cache.dispatchTreeTable[index];
							console.log('检查行数据:', index, data);
							// 确保是子级行：有parentWorkOrderCode且不是父级行
							if(data && data.parentWorkOrderCode === workOrderCode && !data.isParentRow) {
								$row.hide();
								console.log('隐藏子级行:', data.id, '工单编号:', data.productionWorkOrderCode);
							}
						}
					});
				} else {
					// 展开子级行
					$icon.addClass('expanded');
					$icon.removeClass('layui-icon-down').addClass('layui-icon-up');

					// 查找并显示子级行
					$('#dispatchTreeTable').next('.layui-table-view').find('.layui-table-body tbody tr').each(function() {
						var $row = $(this);
						var index = $row.data('index');
						if(typeof index !== 'undefined') {
							var data = table.cache.dispatchTreeTable[index];
							console.log('检查行数据:', index, data);
							// 确保是子级行：有parentWorkOrderCode且不是父级行
							if(data && data.parentWorkOrderCode === workOrderCode && !data.isParentRow) {
								$row.show();
								console.log('显示子级行:', data.id, '工单编号:', data.productionWorkOrderCode);
							}
						}
					});
				}
			};

			// 使用事件委托绑定三角形图标点击事件
			$(document).on('click', '.expand-icon', function(e) {
				e.preventDefault();
				e.stopPropagation();
				var workOrderCode = $(this).data('workorder');
				console.log('点击三角形图标，工单编号:', workOrderCode);
				window.toggleSubRows(workOrderCode, this);
			});

			// 确保点击整个工单编号单元格也能触发展开收起
			$(document).on('click', '.main-row-workorder', function(e) {
				var $icon = $(this).find('.expand-icon');
				if($icon.length > 0) {
					e.preventDefault();
					e.stopPropagation();
					var workOrderCode = $icon.data('workorder');
					console.log('点击工单编号区域，工单编号:', workOrderCode);
					window.toggleSubRows(workOrderCode, $icon[0]);
				}
			});



			// 搜索功能
			form.on('submit(search)', function(data) {
				tableIns.reload({
					where: data.field,
					page: {curr: 1}
				});
				return false;
			});



            // 表头工具栏事件
            table.on('toolbar(dispatchTreeTable)', function(obj) {
                var config = obj.config;
                var tableId = config.id;
                var checkStatus = table.checkStatus(tableId);
                
                if(obj.event === 'getChecked') {
                    // 批量编辑指派人
                    var checkedData = checkStatus.data.filter(function(item) {
                        return !item.isParentRow; // 只处理子级行数据
                    });
                    
                    if(checkedData.length === 0) {
                        layer.msg('请选择要编辑的记录！', {icon: 0});
                        return;
                    }
                    
                    // 显示人员选择弹窗
                    showPersonSelectModal(checkedData);
                } else if(obj.event === 'batchDelete') {
                    // 批量删除
                    var checkedData = checkStatus.data.filter(function(item) {
                        return !item.isParentRow; // 只处理子级行数据
                    });
                    
                    if(checkedData.length === 0) {
                        layer.msg('请选择要删除的记录！', {icon: 0});
                        return;
                    }
                    
                    layer.confirm('确定要删除选中的 ' + checkedData.length + ' 条记录吗？', {
                        icon: 3,
                        title: '删除确认'
                    }, function(index) {
                        var ids = checkedData.map(function(item) {
                            return item.id || item.Id;
                        });
                        
                        $.ajax({
                            url: '/ProductionDispatchMain/BatchDelete',
                            type: 'POST',
                            data: {
                                ids: ids.join(',')
                            },
                            success: function(response) {
                                if(response.success) {
                                    layer.msg('批量删除成功！', {icon: 1});
                                    tableIns.reload();
                                } else {
                                    layer.msg('批量删除失败：' + response.message, {icon: 2});
                                }
                            },
                            error: function() {
                                layer.msg('操作失败，请重试！', {icon: 2});
                            }
                        });
                        layer.close(index);
                    });
                }
            });

			// 单元格工具事件
			table.on('tool(dispatchTreeTable)', function(obj) {
				var data = obj.data;
				var layEvent = obj.event;

				if(layEvent === 'edit') {
					// 修改功能
					console.log('点击修改按钮，数据:', data);
					console.log('data.id:', data.id);
					console.log('data.Id:', data.Id);
					console.log('data.isParentRow:', data.isParentRow);

					// 如果是父级行，不允许修改
					if(data.isParentRow) {
						layer.msg('父级汇总行不能修改，请选择具体的派单记录进行修改！', {icon: 0});
						return;
					}

					var recordId = data.id || data.Id;
					console.log('使用的ID:', recordId);

					if(!recordId || recordId.toString().startsWith('parent_') || recordId.toString().startsWith('child_')) {
						layer.msg('无效的记录ID，无法进行修改操作！', {icon: 2});
						console.error('无效的记录ID:', recordId);
						return;
					}

					layer.open({
						type: 2,
						title: '修改生产派单',
						area: ['80%', '80%'],
						content: '/ProductionDispatchMain/EditDispatch?id=' + recordId
					});
				} else if(layEvent === 'delete') {
					// 删除单条记录
					layer.confirm('确定要删除这条记录吗？', {
						icon: 3,
						title: '删除确认'
					}, function(index) {
						$.ajax({
							url: '/ProductionDispatchMain/Delete',
							type: 'POST',
							data: {
								id: data.id || data.Id
							},
							success: function(response) {
								if(response.success) {
									layer.msg('删除成功！', {icon: 1});
									tableIns.reload();
								} else {
									layer.msg('删除失败：' + response.message, {icon: 2});
								}
							},
							error: function() {
								layer.msg('操作失败，请重试！', {icon: 2});
							}
						});
						layer.close(index);
					});
				} else if(layEvent === 'addChild') {
					// 添加子级功能
					console.log('点击添加子级按钮，父级数据:', data);

					// 确保是父级行
					if(!data.isParentRow) {
						layer.msg('只有父级行才能添加子级！', {icon: 0});
						return;
					}

					// 打开添加子级页面，传递父级工单编号
					layer.open({
						type: 2,
						title: '添加子级派单 - ' + data.productionWorkOrderCode,
						area: ['80%', '80%'],
						content: '/ProductionDispatchMain/AddDispatch?parentWorkOrderCode=' + encodeURIComponent(data.productionWorkOrderCode)
					});
				}
			});
		});

		// 显示人员选择弹窗
		function showPersonSelectModal(checkedData) {
			var modalHtml = `
				<div style="padding: 20px; max-height: 600px; overflow-y: auto;">
					<div style="margin-bottom: 20px; padding: 15px; background-color: #f8f9fa; border-radius: 4px;">
						<h3 style="margin: 0 0 10px 0; font-size: 16px; color: #333;">人员选择</h3>
						<p style="margin: 0; color: #666; font-size: 14px;">已选择 <strong>${checkedData.length}</strong> 条记录进行批量编辑</p>
					</div>

					<!-- 搜索区域 -->
					<div style="margin-bottom: 15px; padding: 15px; background-color: #f8f8f8; border-radius: 4px;">
						<form class="layui-form" lay-filter="personSearchForm" style="margin: 0;">
							<div class="layui-form-item" style="margin-bottom: 10px;">
								<div class="layui-inline" style="margin-right: 15px;">
									<label class="layui-form-label" style="width: 80px;">用户名称</label>
									<div class="layui-input-inline" style="width: 150px; margin-left: 90px;">
										<input type="text" name="userName" placeholder="请输入用户名称" autocomplete="off" class="layui-input">
									</div>
								</div>
								<div class="layui-inline" style="margin-right: 15px;">
									<label class="layui-form-label" style="width: 80px;">手机号码</label>
									<div class="layui-input-inline" style="width: 150px; margin-left: 90px;">
										<input type="text" name="userPhone" placeholder="请输入手机号码" autocomplete="off" class="layui-input">
									</div>
								</div>
								<div class="layui-inline">
									<button class="layui-btn layui-btn-sm" lay-submit lay-filter="personSearch">
										<i class="layui-icon layui-icon-search"></i>搜索
									</button>
									<button type="reset" class="layui-btn layui-btn-primary layui-btn-sm">
										<i class="layui-icon layui-icon-refresh"></i>重置
									</button>
								</div>
							</div>
						</form>
					</div>

					<!-- 人员列表 -->
					<div style="border: 1px solid #e9ecef; border-radius: 4px; max-height: 350px; overflow-y: auto;">
						<table class="layui-table" style="margin: 0;">
							<thead>
								<tr style="background-color: #f8f9fa;">
									<th style="width: 50px; text-align: center;">选择</th>
									<th style="width: 120px;">用户名称</th>
									<th style="width: 100px;">部门</th>
									<th style="width: 120px;">手机号码</th>
									<th>状态</th>
								</tr>
							</thead>
							<tbody id="personTableBody">
								<tr>
									<td colspan="5" style="text-align: center; padding: 20px; color: #999;">
										<i class="layui-icon layui-icon-loading layui-anim layui-anim-rotate layui-anim-loop"></i>
										正在加载人员数据...
									</td>
								</tr>
							</tbody>
						</table>
					</div>

					<!-- 分页 -->
					<div id="personPagination" style="margin-top: 15px; text-align: center;"></div>

					<!-- 操作按钮 -->
					<div style="margin-top: 20px; text-align: center; border-top: 1px solid #e9ecef; padding-top: 15px;">
						<button class="layui-btn" onclick="confirmPersonSelection()">
							<i class="layui-icon layui-icon-ok"></i>确定
						</button>
						<button class="layui-btn layui-btn-primary" onclick="layer.closeAll()">
							<i class="layui-icon layui-icon-close"></i>取消
						</button>
					</div>
				</div>
			`;

			var personSelectIndex = layer.open({
				type: 1,
				title: '人员选择',
				area: ['800px', '700px'],
				content: modalHtml,
				success: function(layero, index) {
					// 重新渲染表单
					layui.use(['form'], function(){
						var modalForm = layui.form;
						modalForm.render();

						// 存储选中的数据和弹窗索引
						window.currentCheckedData = checkedData;
						window.currentPersonSelectIndex = index;
						window.modalForm = modalForm; // 存储到全局变量供其他函数使用

						// 加载人员数据
						loadPersonData();

						// 绑定搜索事件
						modalForm.on('submit(personSearch)', function(data) {
							loadPersonData(data.field);
							return false;
						});

						// 绑定重置按钮事件
						$('button[type="reset"]').on('click', function() {
							// 清空表单
							$('input[name="userName"]').val('');
							$('input[name="userPhone"]').val('');
							// 重新加载所有人员数据
							loadPersonData();
						});
					});
				}
			});
		}

		// 加载人员数据
		function loadPersonData(searchParams) {
			// 显示加载状态
			$('#personTableBody').html(`
				<tr>
					<td colspan="5" style="text-align: center; padding: 20px; color: #999;">
						<i class="layui-icon layui-icon-loading layui-anim layui-anim-rotate layui-anim-loop"></i>
						正在加载人员数据...
					</td>
				</tr>
			`);

			$.ajax({
				url: '/User/ShowUser',
				type: 'GET',
				dataType: 'json',
				success: function(response) {
					console.log('获取人员数据成功:', response);
					var users = response;
					if(response && response.Data) {
						users = response.Data;
					}

					// 如果有搜索参数，在前端进行过滤
					if(searchParams && (searchParams.userName || searchParams.userPhone)) {
						users = filterUsers(users, searchParams);
					}

					renderPersonTable(users || []);
				},
				error: function(xhr, status, error) {
					console.log('获取人员数据失败:', error);
					$('#personTableBody').html(`
						<tr>
							<td colspan="5" style="text-align: center; padding: 20px; color: #f56c6c;">
								<i class="layui-icon layui-icon-close"></i>
								获取人员数据失败，请稍后重试
							</td>
						</tr>
					`);
				}
			});
		}

		// 前端过滤用户数据
		function filterUsers(users, searchParams) {
			if(!users || users.length === 0) return users;

			return users.filter(function(user) {
				var matchUserName = true;
				var matchUserPhone = true;

				// 按用户名称过滤
				if(searchParams.userName && searchParams.userName.trim()) {
					var userName = (user.userName || '').toLowerCase();
					var userNickName = (user.userNickName || '').toLowerCase();
					var searchName = searchParams.userName.trim().toLowerCase();
					matchUserName = userName.includes(searchName) || userNickName.includes(searchName);
				}

				// 按手机号码过滤
				if(searchParams.userPhone && searchParams.userPhone.trim()) {
					var userPhone = (user.userPhone || '').toLowerCase();
					var searchPhone = searchParams.userPhone.trim().toLowerCase();
					matchUserPhone = userPhone.includes(searchPhone);
				}

				return matchUserName && matchUserPhone;
			});
		}

		// 渲染人员表格
		function renderPersonTable(users) {
			var tbody = $('#personTableBody');
			tbody.empty();

			if(!users || users.length === 0) {
				tbody.html(`
					<tr>
						<td colspan="5" style="text-align: center; padding: 20px; color: #999;">
							<i class="layui-icon layui-icon-face-cry"></i>
							暂无人员数据
						</td>
					</tr>
				`);
				return;
			}

			users.forEach(function(user, index) {
				var row = `
					<tr>
						<td style="text-align: center;">
							<input type="radio" name="selectedPerson" value="${user.userName}"
								   data-userid="${user.id}" data-username="${user.userName}"
								   data-userphone="${user.userPhone}" data-department="${user.departmentName || '未分配'}"
								   title="">
						</td>
						<td>${user.userName || ''}</td>
						<td>${user.departmentName || '未分配'}</td>
						<td>${user.userPhone || ''}</td>
						<td>
							<span class="layui-badge layui-bg-blue">
								<i class="layui-icon layui-icon-ok"></i>启用
							</span>
						</td>
					</tr>
				`;
				tbody.append(row);
			});

			// 重新渲染表单元素
			if(window.modalForm) {
				window.modalForm.render('radio');
			}

			// 绑定单选按钮变化事件
			$('input[name="selectedPerson"]').on('change', function() {
				if($(this).is(':checked')) {
					var userName = $(this).data('username');
					console.log('选中了人员:', userName);
				}
			});
		}

		// 确认人员选择
		function confirmPersonSelection() {
			var selectedRadio = $('input[name="selectedPerson"]:checked');

			if(selectedRadio.length === 0) {
				layer.msg('请选择一个人员！', {icon: 0});
				return;
			}

			var selectedUserName = selectedRadio.data('username');
			var selectedUserId = selectedRadio.data('userid');

			if(!selectedUserName) {
				layer.msg('选择的人员信息无效！', {icon: 2});
				return;
			}

			// 显示确认对话框
			layer.confirm('确定要将选中的 ' + window.currentCheckedData.length + ' 条记录的指派人设置为 "' + selectedUserName + '" 吗？', {
				icon: 3,
				title: '确认批量编辑'
			}, function(confirmIndex) {
				// 执行批量更新
				var ids = window.currentCheckedData.map(function(item) {
					return item.id || item.Id;
				});

				var loadIndex = layer.load(2, {
					shade: [0.3, '#000']
				});

				$.ajax({
					url: '/ProductionDispatchMain/BatchUpdateAssignee',
					type: 'POST',
					data: {
						ids: ids.join(','),
						assignee: selectedUserName
					},
					success: function(response) {
						layer.close(loadIndex);
						if(response.success) {
							layer.msg('批量编辑成功！已更新 ' + window.currentCheckedData.length + ' 条记录的指派人为 "' + selectedUserName + '"', {
								icon: 1,
								time: 3000
							});

							// 关闭所有弹窗
							layer.closeAll();

							// 刷新表格，确保显示最新的指派人信息
							setTimeout(function() {
								tableIns.reload();
								form.render('table', 'dispatchTreeTable'); //更新 lay-filter="dispatchTreeTable" 所在容器 table 状态
							}, 800);
						} else {
							layer.msg('批量编辑失败：' + response.message, {icon: 2});
						}
					},
					error: function() {
						layer.close(loadIndex);
						layer.msg('操作失败，请重试！', {icon: 2});
					}
				});

				layer.close(confirmIndex);
			});
		}

		// 页面加载完成后的初始化
		$(document).ready(function() {
			console.log('页面初始化完成');

			// 添加全局点击监听，用于调试
			$(document).on('click', '*', function(e) {
				if($(e.target).hasClass('expand-icon')) {
					console.log('检测到三角形图标被点击');
				}
			});
		});
	</script>
</body>
</html>

